package com.xyoto.community.service.impl;

import com.xyoto.community.cache.CacheInstruction;
import com.xyoto.community.cache.UserCache;
import com.xyoto.community.config.DynamicHotOperateAddScoreConfig;
import com.xyoto.community.constant.*;
import com.xyoto.community.dto.PageDTO;
import com.xyoto.community.entity.comment.DynamicComment;
import com.xyoto.community.entity.love.DynamicLove;
import com.xyoto.community.entity.main.AnonymousUser;
import com.xyoto.community.entity.main.Dynamic;
import com.xyoto.community.entity.main.DynamicForward;
import com.xyoto.community.entity.main.Topic;
import com.xyoto.community.mapper.comment.DynamicCommentMapper;
import com.xyoto.community.mapper.love.DynamicLoveMapper;
import com.xyoto.community.mapper.main.DynamicForwardMapper;
import com.xyoto.community.mapper.main.DynamicMapper;
import com.xyoto.community.mapper.main.TopicMapper;
import com.xyoto.community.mapper.picture.DynamicPictureMapper;
import com.xyoto.community.po.DynamicPicturePO;
import com.xyoto.community.po.UserTitlePO;
import com.xyoto.community.pojo.DynamicStatistic;
import com.xyoto.community.service.*;
import com.xyoto.community.utils.JwtUtils;
import com.xyoto.community.utils.PageUtils;
import com.xyoto.community.utils.RedisCommonUtils;
import com.xyoto.community.vo.TotalDynamicListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Author: 廖振辉
 * Date: 2021/12/2
 * Description: 动态缓存实现类
 */
@Slf4j
@Service
public class DynamicCacheServiceImpl implements DynamicCacheService {

    @Autowired
    private RedisCommonUtils redisCommonUtils;

    @Autowired
    private DynamicMapper dynamicMapper;

    Random random = new Random();

    @Autowired
    private DynamicHotOperateAddScoreConfig dynamicHotOperateAddScoreConfig;

    @Autowired
    private DynamicLoveMapper dynamicLoveMapper;

    @Autowired
    private DynamicCommentMapper dynamicCommentMapper;

    @Autowired
    private DynamicForwardMapper dynamicForwardMapper;

    @Resource
    private HttpServletRequest request;

    @Autowired
    private UserCacheService userCacheService;

    @Autowired
    private AnonymousCacheService anonymousCacheService;

    @Autowired
    private DynamicPictureMapper dynamicPictureMapper;

    @Autowired
    private UserTitleService userTitleService;

    @Autowired
    private TopicCacheService topicCacheService;

    @Autowired
    private TopicAllDynamicCacheService topicAllDynamicCacheService;

    @Autowired
    private UserTitleCacheService userTitleCacheService;

    @Autowired
    private PictureCacheService pictureCacheService;

    /**
     * 加载一条动态到redis
     *
     * @param dynamic 动态
     * @author 廖振辉
     */
    private void loadDynamic2Cache(Dynamic dynamic) {
        if (dynamic == null) {
            return;
        }
        // 判断判断Redis中当前动态详情总条数，如果小于50000条则放入redis
        long size = redisCommonUtils.hlen(CacheInstruction.DYNAMIC);
        if (size < CacheInstruction.DYNAMIC_MAX_SAVE_COUNT) {
            // 过期时间 + 5%的随机值
            redisCommonUtils.hset(CacheInstruction.DYNAMIC, dynamic.getId().toString()
                    , dynamic, CacheInstruction.DYNAMIC_EXPIRE_TIME + random.nextInt((int) (CacheInstruction.DYNAMIC_EXPIRE_TIME * 0.05)));
        }
    }

    /**
     * 根据动态id从redis中获取动态
     *
     * @param dynamicId
     * @return {@link Dynamic}
     * @author 廖振辉
     */
    @Override
    public Dynamic getDynamicByDynamicId(Integer dynamicId) {
        Dynamic dynamicFromCache = (Dynamic) redisCommonUtils.hget(CacheInstruction.DYNAMIC, dynamicId.toString());
        if (dynamicFromCache == null) {
            // 从db中获取动态
            Dynamic dynamic = dynamicMapper.selectOneByDynamicId(dynamicId);
            dynamicFromCache = dynamic;
            if (dynamic != null && Short.valueOf(DeleteStatus.NO).equals(dynamic.getDeleteStatus())) {
                // 动态没被删除，则保存到缓存
                this.loadDynamic2Cache(dynamic);
            }
            // 如果动态已删除
            if (dynamic != null && Short.valueOf(DeleteStatus.YES).equals(dynamic.getDeleteStatus())) {
                dynamicFromCache = null;
            }
        }
        return dynamicFromCache;
    }

    /**
     * 获取热门动态id
     *
     * @param pageDTO
     * @return {@link PageUtils< Integer>}
     * @author 廖振辉
     */
    @Override
    public PageUtils<Integer> getHotDynamicIdPage(PageDTO pageDTO) {
        Long total = redisCommonUtils.getZsetSize(CacheInstruction.HOT_DYNAMIC_ID_SET);
        if (total <= 0){
            return PageUtils.restPage(new ArrayList<>());
        }
        PageUtils<Integer> hotDynamicIdPage = new PageUtils<>();
        long totalPage = total % pageDTO.getPageSize() == 0 ? total / pageDTO.getPageSize() : total / pageDTO.getPageSize() + 1;
        hotDynamicIdPage.setTotal(total);
        hotDynamicIdPage.setTotalPage((int) totalPage);
        List<Integer> dynamicIds = topicAllDynamicCacheService.getTopicDynamicIdsFromCache(CacheInstruction.HOT_DYNAMIC_ID_SET, pageDTO);
        hotDynamicIdPage.setList(dynamicIds);
        hotDynamicIdPage.setPageSize(pageDTO.getPageSize());
        // 从redis中拿出该页的热门动态id
        int start = (pageDTO.getPageNum() - 1) * pageDTO.getPageSize();
        int end = start + pageDTO.getPageSize();
        Set<Object> hotDynamicIdSet = redisCommonUtils.rangeByZSet(CacheInstruction.HOT_DYNAMIC_ID_SET, start, end);
        ArrayList<Integer> hotDynamicIdList = new ArrayList<>(hotDynamicIdSet.size());
        for (Object hotDynamicId : hotDynamicIdSet) {
            hotDynamicIdList.add(Integer.valueOf(hotDynamicId.toString()));
        }
        hotDynamicIdPage.setList(hotDynamicIdList);
        return hotDynamicIdPage;
    }

    /**
     * 从缓存中取最新的500条动态id（分页获取）
     *
     * @param pageDTO
     * @return {@link PageUtils< Integer>}
     * @author 廖振辉
     */
    @Override
    public PageUtils<Integer> getTotalDynamicIdPage(PageDTO pageDTO) {
        // 获取动态总数
        int count = getTotalDynamicCount();
        int totalPage = count % pageDTO.getPageSize() == 0 ? count / pageDTO.getPageSize() : count / pageDTO.getPageSize() + 1;
        PageUtils<Integer> dynamicIdPage = new PageUtils<>();
        dynamicIdPage.setPageSize(pageDTO.getPageSize());
        dynamicIdPage.setTotalPage(totalPage);
        dynamicIdPage.setTotal((long) count);
        dynamicIdPage.setPageNum(pageDTO.getPageNum());
        List<Integer> dynamicIds = topicAllDynamicCacheService.getTopicDynamicIdsFromCache(CacheInstruction.LATEST_DYNAMIC_ID_SET, pageDTO);
        dynamicIdPage.setList(dynamicIds);
        return dynamicIdPage;
    }

    /**
     * 将动态缓存到redis
     *
     * @param dynamic
     * @return {@link }
     * @author 廖振辉
     */
    @Override
    @Async
    public void saveDynamic2Cache(Dynamic dynamic, Integer operateType) {
        if (dynamic == null || dynamic.getId() == null
                || Short.valueOf(PersonalStatus.VISIBLE_TO_PERSONAL).equals(dynamic.getPersonal())) {
            // 如果动态为私密、则不缓存到redis
            return;
        }
        // 将动态全量数据缓存到redis中
        this.loadDynamic2Cache(dynamic);
        // 将动态id放到redis的最新的500条动态id中
        this.saveDynamic2LatestDynamicIdSet(dynamic);
        // 将动态保存到热门动态
        this.saveHotDynamic2HotDynamicSet(dynamic, operateType);
    }

    @Override
    public void updateDynamicInCache(Dynamic dynamic) {
        if (dynamic == null || dynamic.getId() == null) {
            return;
        }

        if (Short.valueOf(DeleteStatus.YES).equals(dynamic.getDeleteStatus())) {
            // 删除redis中该动态的全量数据
            redisCommonUtils.hdel(CacheInstruction.DYNAMIC, dynamic.getId().toString());
        } else if (redisCommonUtils.hget(CacheInstruction.DYNAMIC, dynamic.getId()) != null) {
            // 若存中有动态则更新
            redisCommonUtils.hset(CacheInstruction.DYNAMIC, dynamic.getId(), dynamic);
        }

        if (Short.valueOf(DeleteStatus.YES).equals(dynamic.getDeleteStatus())
                || Short.valueOf(PersonalStatus.VISIBLE_TO_PERSONAL).equals(dynamic.getPersonal())) {
            // 将该动态从热门动态id列表中删除
            redisCommonUtils.removeZSetValue(CacheInstruction.HOT_DYNAMIC_ID_SET, dynamic.getId());
            // 将动态从最新的500条动态id中删除
            redisCommonUtils.removeZSetValue(CacheInstruction.LATEST_DYNAMIC_ID_SET, dynamic.getId());
        } else if (Short.valueOf(PersonalStatus.VISIBLE_TO_ALL).equals(dynamic.getPersonal())) {
            // 将动态放回到最新的500条动态id中
            this.saveDynamic2LatestDynamicIdSet(dynamic);
        }

    }

    /**
     * 根据动态id拿到动态的点赞、评论、转发数
     *
     * @param dynamicId
     * @return {@link DynamicStatistic}
     * @author 廖振辉
     */
    @Override
    public DynamicStatistic getDynamicStatistic(Integer dynamicId) {
        if (dynamicId == null) {
            return null;
        }
        // 获取点赞数
        int dynamicLoveCountFromCache = this.getDynamicLoveCountFromCache(dynamicId);

        // 获取转发数
        int dynamicForwardCountFromCache = this.getDynamicForwardCountFromCache(dynamicId);

        // 获取评论数
        int dynamicCommentCountFromCache = this.getDynamicCommentCountFromCache(dynamicId);

        return new DynamicStatistic(dynamicId, dynamicLoveCountFromCache
                , dynamicCommentCountFromCache, dynamicForwardCountFromCache);
    }

    /**
     * 更新缓存中的动态评论数
     *
     * @param dynamicComment
     * @return {@link}
     * @author 廖振辉
     */
    @Override
    @Async
    public void updateDynamicCommentCountInCache(DynamicComment dynamicComment) {
        if (dynamicComment == null) {
            return;
        }
        if (redisCommonUtils.hget(CacheInstruction.DYNAMIC_COMMENT_COUNT, dynamicComment.getDynamicId()) == null) {
            return;
        }
        if (Short.valueOf(DeleteStatus.YES).equals(dynamicComment.getDeleteStatus())) {
            // 减少评论数
            redisCommonUtils.hdecr(CacheInstruction.DYNAMIC_COMMENT_COUNT, dynamicComment.getDynamicId().toString(), 1.0);
        } else {
            // 增加评论数
            redisCommonUtils.hincr(CacheInstruction.DYNAMIC_COMMENT_COUNT, dynamicComment.getDynamicId().toString(), 1.0);
        }
    }

    /**
     * 更新缓存中的动态点赞数
     *
     * @param dynamicLove
     * @return {@link}
     * @author 廖振辉
     */
    @Override
    @Async
    public void updateDynamicLoveCountInCache(DynamicLove dynamicLove) {
        if (dynamicLove == null) {
            return;
        }
        if (redisCommonUtils.hget(CacheInstruction.DYNAMIC_LOVE_COUNT, dynamicLove.getDynamicId()) == null) {
            return;
        }
        if (Short.valueOf(LoveStatus.UN_LOVE).equals(dynamicLove.getStatus())) {
            // 减少点赞数
            redisCommonUtils.hdecr(CacheInstruction.DYNAMIC_LOVE_COUNT, dynamicLove.getDynamicId().toString(), 1.0);
        } else {
            // 增加点赞数
            redisCommonUtils.hincr(CacheInstruction.DYNAMIC_LOVE_COUNT, dynamicLove.getDynamicId().toString(), 1.0);
        }
    }

    /**
     * 更新缓存中的动态转发数
     *
     * @param dynamicForward
     * @return {@link}
     * @author 廖振辉
     */
    @Override
    @Async
    public void updateDynamicForwardCountInCache(DynamicForward dynamicForward) {
        if (dynamicForward == null) {
            return;
        }
        if (redisCommonUtils.hget(CacheInstruction.DYNAMIC_FORWARD_COUNT, dynamicForward.getDynamicId()) == null) {
            return;
        }
        // 增加点赞数
        redisCommonUtils.hincr(CacheInstruction.DYNAMIC_FORWARD_COUNT, dynamicForward.getDynamicId().toString(), 1.0);
    }

    @Override
    public List<TotalDynamicListVo> getDynamicVoListFromCache(PageUtils<Integer> totalDynamicIdPage) {

        //获取动态id集合
        List<Integer> dynamicIds = totalDynamicIdPage.getList();
        //获取本人的id
        Integer meId = JwtUtils.getMemberIdByJwtToken(request);
        //构造存储结果的容器
        List<TotalDynamicListVo> totalDynamicListVoList = new ArrayList<>(totalDynamicIdPage.getPageSize());
        //通过循环拼接数据
        for (Integer dynamicId : dynamicIds) {
            TotalDynamicListVo totalDynamicListVo =  new TotalDynamicListVo();
            //从缓存中获取动态的信息
            Dynamic dynamic = getDynamicByDynamicId(dynamicId);
            if (dynamic == null){
                continue;
            }
            //存储动态的基本信息
            totalDynamicListVo.setId(dynamic.getId());
            totalDynamicListVo.setContent(dynamic.getContent());
            totalDynamicListVo.setDynamicPlace(dynamic.getDynamicPlace());
            totalDynamicListVo.setCreateTime(dynamic.getCreateTime());

            //判断当前动态是否为匿名动态 存储动态的用户信息
            if (Integer.valueOf(AnonymousStatus.ANONYMOUS).equals(dynamic.getStatus()) && dynamic.getAnonymousUserId() != null){
                AnonymousUser anonymousUser = anonymousCacheService.updateAnonymousCacheList(dynamic.getAnonymousUserId());
                totalDynamicListVo.setUserId(null);
                totalDynamicListVo.setNickname(anonymousUser.getAnonymousName());
                totalDynamicListVo.setAvatarUrl(anonymousUser.getAnonymousAvatarUrl());
            }else {
                UserCache userCache = userCacheService.getUserMessageFromUserCacheById(dynamic.getUserId());
                totalDynamicListVo.setUserId(userCache.getId());
                totalDynamicListVo.setNickname(userCache.getNickname());
                totalDynamicListVo.setAvatarUrl(userCache.getAvatarUrl());
                // 获取头衔
                UserTitlePO userTitlePo = userTitleCacheService.getUserTitleFromCache(userCache.getTitleNameId(), userCache.getTitleLogoId());
                totalDynamicListVo.setUserTitlePO(userTitlePo);
            }


             //存储动态的话题信息
            if (dynamic.getTopicId() != null && dynamic.getTopicId() != 0){
                Topic topic = topicCacheService.getTopicMessageFromCache(dynamic.getTopicId());
                totalDynamicListVo.setTopicId(topic.getId());
                totalDynamicListVo.setTitle(topic.getTitle());
            }
            //存储动态的点赞数、评论数、转发数
            totalDynamicListVo.setDynamicLoveCount(getDynamicLoveCountFromCache(dynamicId));
            totalDynamicListVo.setDynamicForwardCount(getDynamicForwardCountFromCache(dynamicId));
            totalDynamicListVo.setDynamicCommentCount(getDynamicCommentCountFromCache(dynamicId));

            //存储用户的点赞状态
            boolean flag = userCacheService.getUserDynamicLoveStatusFromCache(meId, dynamicId);
            if (flag){
                totalDynamicListVo.setLoveStatus(LoveStatus.LOVE);
            }else {
                totalDynamicListVo.setLoveStatus(LoveStatus.UN_LOVE);
            }

            //存储用户的关注状态
            boolean flag2 = userCacheService.getUserFollowStatus(meId, dynamic.getUserId());
            if (flag2){
                totalDynamicListVo.setFollowStatus(FollowStatus.FOLLOW);
            }else {
                totalDynamicListVo.setFollowStatus(FollowStatus.UN_FOLLOW);
            }

            //加入动态图片
            List<DynamicPicturePO> dynamicPictures = pictureCacheService.getDynamicPicturePoFromCache(dynamicId);
            totalDynamicListVo.setDynamicPicturePo(dynamicPictures);
            totalDynamicListVoList.add(totalDynamicListVo);
        }
        return totalDynamicListVoList;

    }

    /**
     * 增加缓存中动态的总数
     * @author 廖振辉
     * @param dynamic
     * @return {@link}
     */
    @Override
    @Async
    public void updateDynamicCountInCache(Dynamic dynamic) {
        if (dynamic == null){
            return;
        }
        if (Short.valueOf(DeleteStatus.NO).equals(dynamic.getDeleteStatus())){
            // 新增动态，增加动态总数 + 1
            redisCommonUtils.hincr(CacheInstruction.DYNAMIC_COUNT,Integer.valueOf(0).toString(),1.0);

            // 如果有话题，则还需要增加对应话题的动态数
            Integer topicId = dynamic.getTopicId();
            if (topicId != null && topicId != 0){
                redisCommonUtils.hincr(CacheInstruction.DYNAMIC_COUNT,topicId.toString(),1.0);
            }
        }else {
            // 删除动态，减少动态的总数
            redisCommonUtils.hdecr(CacheInstruction.DYNAMIC_COUNT,Integer.valueOf(0).toString(),1.0);

            // 如果有话题，则还需要减少对应话题的动态数
            Integer topicId = dynamic.getTopicId();
            if (topicId != null && topicId != 0){
                redisCommonUtils.hdecr(CacheInstruction.DYNAMIC_COUNT,topicId.toString(),1.0);
            }
        }
    }

    /**
     * 获取全部动态的数量
     * @author 廖振辉
     * @return {@link int}
     */
    @Override
    public int getTotalDynamicCount() {
        return getTopicDynamicCount(null);
    }

    /**
     * 从缓存中获取话题下的动态数量
     * @author 廖振辉
     * @param topicId
     * @return {@link int} 返回指定话题下的动态数量，如果话题id为null或0，则返回的是全部动态数量
     */
    @Override
    public int getTopicDynamicCount(Integer topicId) {
        Object count;
        if (topicId == null || topicId == 0){
            count = redisCommonUtils.hget(CacheInstruction.DYNAMIC_COUNT, Integer.valueOf(0).toString());
            // 缓存中没有则从数据库从拿
            if (count == null){
                count = dynamicMapper.countDynamicByStatusAndPersonal(DeleteStatus.NO, PersonalStatus.VISIBLE_TO_ALL);
            }
            //将数据更新到redis中
            redisCommonUtils.hset(CacheInstruction.DYNAMIC_COUNT,Integer.valueOf(0).toString(),count);
        }else {
            count = redisCommonUtils.hget(CacheInstruction.DYNAMIC_COUNT, topicId.toString());
            // 缓存中没有则从数据库从拿
            if (count == null){
                count = dynamicMapper.countDynamicByTopicIdAndStatusAndPersonal(
                        topicId,DeleteStatus.NO,PersonalStatus.VISIBLE_TO_ALL);
            }
            //将数据更新到redis中
            redisCommonUtils.hset(CacheInstruction.DYNAMIC_COUNT,topicId.toString(),count);
        }
        return (int) count;
    }

    /**
     * 获取动态的点赞数，若缓存中没有，则会从db取，并根据缓存的情况判断是否需要放入redis
     *
     * @param dynamicId
     * @return {@link int}
     * @author 廖振辉
     */
    private int getDynamicLoveCountFromCache(Integer dynamicId) {
        Object loveCountFromCache = redisCommonUtils.hget(CacheInstruction.DYNAMIC_LOVE_COUNT, dynamicId.toString());
        int loveCount;
        if (loveCountFromCache == null) {
            loveCount = dynamicLoveMapper.countDynamicLikeById(dynamicId, DeleteStatus.NO);
            // 判断是否需要将点赞数放入redis
            long dynamicCount = redisCommonUtils.hlen(CacheInstruction.DYNAMIC_LOVE_COUNT);
            if (dynamicCount < CacheInstruction.DYNAMIC_MAX_SAVE_COUNT) {
                // 放入redis，过期时间为 3 天 + 5%的随机值
                redisCommonUtils.hset(CacheInstruction.DYNAMIC_LOVE_COUNT
                        , dynamicId.toString(), loveCount, CacheInstruction.DYNAMIC_EXPIRE_TIME
                                + random.nextInt((int) (CacheInstruction.DYNAMIC_EXPIRE_TIME * 0.05)));
            }
        } else {
            loveCount = (int) loveCountFromCache;
        }
        return loveCount;
    }

    /**
     * 获取动态的评论数，若缓存中没有，则会从db取，并根据缓存的情况判断是否需要放入redis
     *
     * @param dynamicId
     * @return {@link int}
     * @author 廖振辉
     */
    private int getDynamicCommentCountFromCache(Integer dynamicId) {
        Object commentCountFromCache = redisCommonUtils.hget(CacheInstruction.DYNAMIC_COMMENT_COUNT, dynamicId.toString());
        int commentCount;
        if (commentCountFromCache == null) {
            commentCount = dynamicCommentMapper.countDynamicCommentById(dynamicId, DeleteStatus.NO);
            // 判断是否需要将评论数放入redis
            long dynamicCount = redisCommonUtils.hlen(CacheInstruction.DYNAMIC_COMMENT_COUNT);
            if (dynamicCount < CacheInstruction.DYNAMIC_MAX_SAVE_COUNT) {
                // 放入redis，过期时间为 3 天 + 5%的随机值
                redisCommonUtils.hset(CacheInstruction.DYNAMIC_COMMENT_COUNT
                        , dynamicId.toString(), commentCount, CacheInstruction.DYNAMIC_EXPIRE_TIME
                                + random.nextInt((int) (CacheInstruction.DYNAMIC_EXPIRE_TIME * 0.05)));
            }
        } else {
            commentCount = (int) commentCountFromCache;
        }
        return commentCount;
    }

    /**
     * 获取动态的评论数，若缓存中没有，则会从db取，并根据缓存的情况判断是否需要放入redis
     *
     * @param dynamicId
     * @return {@link int}
     * @author 廖振辉
     */
    private int getDynamicForwardCountFromCache(Integer dynamicId) {
        Object forwardCountFromCache = redisCommonUtils.hget(CacheInstruction.DYNAMIC_FORWARD_COUNT, dynamicId.toString());
        int forwardCount;
        if (forwardCountFromCache == null) {
            forwardCount = dynamicForwardMapper.countForwardByDynamicId(dynamicId);
            // 判断是否需要将转发数放入redis
            long dynamicCount = redisCommonUtils.hlen(CacheInstruction.DYNAMIC_FORWARD_COUNT);
            if (dynamicCount < CacheInstruction.DYNAMIC_MAX_SAVE_COUNT) {
                // 放入redis，过期时间为 3 天 + 5%的随机值
                redisCommonUtils.hset(CacheInstruction.DYNAMIC_FORWARD_COUNT
                        , dynamicId.toString(), forwardCount, CacheInstruction.DYNAMIC_EXPIRE_TIME
                                + random.nextInt((int) (CacheInstruction.DYNAMIC_EXPIRE_TIME * 0.05)));
            }
        } else {
            forwardCount = (int) forwardCountFromCache;
        }
        return forwardCount;
    }


    /**
     * 将动态加入到最新的500条动态id中
     *
     * @param dynamic
     * @return {@link }
     * @author 廖振辉
     */
    private void saveDynamic2LatestDynamicIdSet(Dynamic dynamic) {
        if (dynamic == null) {
            return;
        }
        if (redisCommonUtils.getZsetSize(CacheInstruction.LATEST_DYNAMIC_ID_SET) < CacheInstruction.LATEST_DYNAMIC_MAX_COUNT) {
            // 如果已经满了500条， 则需要删除掉最早的一条
            redisCommonUtils.removeFirstZSetValue(CacheInstruction.LATEST_DYNAMIC_ID_SET);
        }
        // 将新增的动态id放入到redis中，并设置七天 + 5% 的随机时间过期
        redisCommonUtils.zSet(CacheInstruction.LATEST_DYNAMIC_ID_SET, dynamic.getId()
                , (double) dynamic.getCreateTime().getTime()
                , CacheInstruction.LATEST_DYNAMIC_EXPIRE_TIME + random.nextInt((int) (CacheInstruction.LATEST_DYNAMIC_EXPIRE_TIME * 0.05)));
    }

    /**
     * 保存热门动态到redis中
     *
     * @param dynamic
     * @param operateType 加分类型
     * @return {@link }
     * @author 廖振辉
     */
    private void saveHotDynamic2HotDynamicSet(Dynamic dynamic, Integer operateType) {
        if (dynamic == null || operateType == null) {
            return;
        }
        // 根据加分类型获取加分值
        Double score = dynamicHotOperateAddScoreConfig.getDynamicIncreaseScoreByOperateType(operateType);
        // 判断该动态是否存在热门动态中，如果存在，则直接加分，否则需要新增进去
        Long zrevrank = redisCommonUtils.zrevrank(CacheInstruction.HOT_DYNAMIC_ID_SET, dynamic.getId());
        if (zrevrank == -1) {
            // 缓存中无该动态
            redisCommonUtils.zSet(CacheInstruction.HOT_DYNAMIC_ID_SET, dynamic.getId(), score,
                    CacheInstruction.HOT_DYNAMIC_EXPIRE_TIME + random.nextInt((int) (CacheInstruction.HOT_DYNAMIC_EXPIRE_TIME * 0.05)));
        } else {
            // 直接加分
            redisCommonUtils.incrementScoreForZSet(CacheInstruction.HOT_DYNAMIC_ID_SET, dynamic.getId(), score);
        }
    }
}
